package com.runa.monitor.platinterface.backwork.impl;

import com.alibaba.fastjson.JSONObject;
import com.runa.monitor.comm.dto.Node;
import com.runa.monitor.comm.dto.newComm.AsynResult;
import com.runa.monitor.platinterface.backwork.function.TaskFunction;
import com.runa.monitor.platinterface.mqtt.MqttUtil;
import com.runa.monitor.platinterface.netservice.connect.commstatus.CommStatus;
import com.runa.rccprotocol.dto.AffirmDeny;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class SubEquWriteTaskFunction implements TaskFunction<Node, Object, Void> {

    private final String task;

    private final String holdInfo;

    private final int priority;

    private Node node;

    public SubEquWriteTaskFunction(String task, String holdInfo, int priority) {
        this.task = task;
        this.holdInfo = holdInfo;
        this.priority = priority;
    }

    @Override
    public void setStatus(Node node) {
        this.node = node;
    }

    @Override
    public void doApply(CommStatus status, Object result) {
        log.info("SubEquWriteTaskFunction doApply {} {} {}", status, JSONObject.toJSONString(node), JSONObject.toJSONString(result));
        AsynResult asynResult = AsynResult.success();
        asynResult.setTask(task);
        asynResult.setHoldInfo(holdInfo);
        if (CommStatus.OK.equals(status)) {
            if (node != null && result instanceof AffirmDeny) {
                asynResult.setIdentity(node.getId());
                AffirmDeny affirmDeny = (AffirmDeny) result;
                if (!affirmDeny.getData()) {
                    asynResult.denySetting();
                }
                MqttUtil.send(MqttUtil.topicOfNoneContentForNode, asynResult);
            }
        } else if (CommStatus.OffLine.equals(status)) {
            List<Node> nodeList = (List<Node>) result;
            for (Node node : nodeList) {
                asynResult.setIdentity(node.getId());
                asynResult.offlineSetting();
                MqttUtil.send(MqttUtil.topicOfNoneContentForNode, asynResult);
            }
        } else if (CommStatus.TimeOut.equals(status)) {
            if (node != null) {
                asynResult.setIdentity(node.getId());
                asynResult.timeoutSetting();
                MqttUtil.send(MqttUtil.topicOfNoneContentForNode, asynResult);
            }
        }
    }

    @Override
    public Void waitResult() {
        return null;
    }

    @Override
    public String getSerial() {
        return null;
    }

    @Override
    public int getPriority() {
        return priority;
    }
}
